import store from '@/store'
import { getCurrentPage } from './common'

const nonAuthUrls = ['/api/register/verify', '/api/login']

const baseUrl = import.meta.env.VITE_APP_BASE_API_URL

/**
 * @param {UniApp.RequestOptions} options
 */
export default function request(options) {
  function handle401() {
    const currentPage = getCurrentPage()
    if (currentPage.path.startsWith('/pages/auth')) {
      return
    }
    if (store.state.user.token) {
      uni.showToast({
        title: '登录超时,请重新登录',
        icon: 'none',
      })
      store.commit('user/clear')
      uni.navigateTo({
        url: '/pages/auth/index',
      })
    } else {
      store.commit('user/clear')
      uni.reLaunch({
        url: '/pages/auth/index',
      })
    }
  }
  return new Promise((resolve, reject) => {
    const { url, header, ...restOptions } = options
    const reqUrl =
      import.meta.env.VITE_APP_PLATFORM === 'h5'
        ? url
        : `${baseUrl}${options.url}`
    uni.request({
      url: reqUrl,
      method: options.method || 'GET',
      header: {
        Authorization: `Bearer ${store.state.user?.token}`,
        ...header,
      },
      ...restOptions,
      success: (res) => {
        const { data, statusCode } = res
        if (nonAuthUrls.includes(options.url)) {
          if (statusCode > 299 || (data.status && data.status > 299)) {
            uni.showToast({
              title: data.msg ?? '网络错误',
              icon: 'none',
            })
          }
          resolve(data)
        } else {
          if (statusCode === 401 || data?.status === 401) {
            handle401()
          } else if (statusCode > 299 || (data.status && data.status > 299)) {
            uni.showToast({
              title: data.msg ?? '网络错误',
              icon: 'none',
            })
          }
          resolve(data)
        }
      },
      fail: (error) => {
        uni.showToast({
          icon: 'none',
          title: '网络错误',
        })
        reject(error)
      },
    })
  })
}
